package info.hexin.mvc.upload;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * 文件上传临时文件。参照nutz中FieldMeta
 * 
 * @author hexin
 * 
 */
public class TempFile {

	private String fileName;
	private String formName;
	// 上传文件的输入流
	private InputStream inputstream;
	private boolean isFile;

	private Map<String, String> map;
	private byte[] data;

	public TempFile(String contentDisposition) {
		// 正则不能解决中文、外文文件名称问题， 参照nutz
		// Matcher formNameMatcher =
		// Http.FORM_NAME_PATTERN.matcher(contentDisposition);
		// Matcher fileNameMatcher =
		// Http.FILE_NAME_PATTERN.matcher(contentDisposition);
		//
		// if (formNameMatcher.find()) {
		// this.formName = formNameMatcher.group(1);
		// }
		//
		// if (fileNameMatcher.find()) {
		// this.isFile = true;
		// this.fileName = fileNameMatcher.group(1);
		// }

		map = new HashMap<String, String>();
		String[] ss = contentDisposition.split("[\n;]");
		for (String pair : ss) {
			String name = pair.split("[:=]")[0];
			String value = pair.replaceAll("^[^=:]*[=:]", "");
			map.put(name.trim(), formatValue(value));
		}
	}

	private static String formatValue(String s) {
		s = s.trim();
		if (null != s && s.length() > 2 && s.charAt(0) == '"')
			return s.substring(1, s.length() - 1);
		if ("\"\"".equals(s))
			return "";
		return s;
	}

	/**
	 * 数据不落地上传
	 * 
	 * @return
	 */
	public InputStream getInputstream() {
		inputstream = new ByteArrayInputStream(this.data);
		return inputstream;
	}

	public String getFileName() {
		return map.get("filename");
	}

	public void setFileByte(byte[] data) {
		this.data = data;
	}

	public String getFileExtension() {
		String name = getFileName();
		int pos = name.lastIndexOf('.');
		if (pos >= 0)
			return name.substring(pos);
		return "";
	}

	public String getFormName() {
		return map.get("name");
	}

	public boolean isFile() {
		return null != getFileName();
	}
}
